import SockJS from 'sockjs-client'

// 动态导入webstomp-client
let Stomp = null

class WebSocketService {
  constructor() {
    this.stompClient = null
    this.connected = false
    this.subscriptions = new Map()
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
  }

  async initStomp() {
    if (Stomp) return Stomp
    
    try {
      // 使用动态导入
      const webstompModule = await import('webstomp-client')
      Stomp = webstompModule.default || webstompModule.Stomp || webstompModule
      return Stomp
    } catch (error) {
      console.error('导入webstomp-client失败:', error)
      throw new Error('无法加载WebSocket客户端库')
    }
  }

  async connect() {
    return new Promise(async (resolve, reject) => {
      try {
        // 确保Stomp已初始化
        const StompClient = await this.initStomp()
        
        const socket = new SockJS('/ws')
        this.stompClient = StompClient.over(socket)
        
        // 设置连接选项
        const connectHeaders = {}
        
        this.stompClient.connect(
          connectHeaders,
          (frame) => {
            console.log('WebSocket连接成功:', frame)
            this.connected = true
            this.reconnectAttempts = 0
            resolve()
          },
          (error) => {
            console.error('WebSocket连接失败:', error)
            this.connected = false
            
            // 自动重连逻辑
            if (this.reconnectAttempts < this.maxReconnectAttempts) {
              this.reconnectAttempts++
              console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`)
              setTimeout(() => {
                this.connect().then(resolve).catch(reject)
              }, 3000)
            } else {
              reject(error)
            }
          }
        )
      } catch (error) {
        console.error('WebSocket初始化失败:', error)
        reject(error)
      }
    })
  }

  disconnect() {
    if (this.stompClient) {
      try {
        this.stompClient.disconnect()
      } catch (error) {
        console.error('WebSocket断开连接失败:', error)
      }
      this.connected = false
      this.subscriptions.clear()
    }
  }

  subscribe(topic, callback) {
    if (!this.stompClient || !this.connected) {
      console.error('WebSocket未连接')
      return null
    }

    try {
      const subscription = this.stompClient.subscribe(topic, (message) => {
        try {
          const data = JSON.parse(message.body)
          callback(data)
        } catch (error) {
          console.error('解析WebSocket消息失败:', error)
          // 如果解析失败，尝试直接传递原始消息
          callback(message)
        }
      })

      this.subscriptions.set(topic, subscription)
      return subscription
    } catch (error) {
      console.error('订阅WebSocket主题失败:', error)
      return null
    }
  }

  unsubscribe(topic) {
    const subscription = this.subscriptions.get(topic)
    if (subscription) {
      try {
        subscription.unsubscribe()
        this.subscriptions.delete(topic)
      } catch (error) {
        console.error('取消订阅失败:', error)
      }
    }
  }

  send(destination, message) {
    if (!this.stompClient || !this.connected) {
      console.error('WebSocket未连接')
      return false
    }

    try {
      this.stompClient.send(destination, {}, JSON.stringify(message))
      return true
    } catch (error) {
      console.error('发送WebSocket消息失败:', error)
      return false
    }
  }

  isConnected() {
    return this.connected
  }

  // 获取连接状态
  getConnectionStatus() {
    return {
      connected: this.connected,
      reconnectAttempts: this.reconnectAttempts,
      maxReconnectAttempts: this.maxReconnectAttempts
    }
  }
}

export default new WebSocketService()

